package 邮件知识;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.List;
import java.util.Arrays;
import java.util.Properties;

public class MultiMailSender {

    public static void main(String[] args) {
        // 1. 设置邮件服务器的基本信息
        String host = "mail.xxx.com"; // 邮件服务器的地址
        String port = "25"; // 邮件服务器的端口号（例如：25是常用的SMTP端口）
        String from = "xx@xx.com"; // 发件人邮箱
        // java11：
        //  List<String> toList = List.of("receiver1@example.com", "receiver2@example.com"); // 收件人邮箱列表
        // java 8
        List<String> toList = Arrays.asList("xx@qq.com", "receiver2@example.com"); // 收件人邮箱列表
        String username = "xx"; // 邮箱用户名
        String password = "xx"; // 邮箱密码

        // 2. 设置邮件内容
        String subject = "邮件主题";
        String body = "邮件正文内容";

        // 3. 创建附件
        File attachment1 = new File("restored.jpg"); // 附件1
        File attachment2 = new File("restored.jpg"); // 附件2

        // 4. 配置邮件会话（使用SSL和SMTP服务器连接）
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        // properties.put("mail.smtp.starttls.enable", "true"); // 启用TLS

        // 5. 创建会话对象并进行身份验证
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 6. 创建邮件消息
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));

            // 设置多个收件人
            for (String to : toList) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            message.setSubject(subject);

            // 创建邮件正文
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(body);

            // 创建附件部分
            MimeBodyPart attachmentPart1 = new MimeBodyPart();
            attachmentPart1.attachFile(attachment1);

            MimeBodyPart attachmentPart2 = new MimeBodyPart();
            attachmentPart2.attachFile(attachment2);

            // 创建多部分邮件
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodyPart);
            multipart.addBodyPart(attachmentPart1);
            multipart.addBodyPart(attachmentPart2);

            message.setContent(multipart);

            // 7. 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}